package com.ywq.app.biz.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.ywq.app.biz.IdentifierBiz;
import com.ywq.app.dao.AuxIdentifierDao;
import com.ywq.app.domain.AuxIdentifier;
import com.ywq.common.exception.AppBusinessException;

/*import cn.sumpu.app.coolsk.biz.IdentifierBiz;
import cn.sumpu.app.coolsk.exception.AppBusinessException;
import cn.sumpu.app.coolsk.dao.AuxIdentifierDao;
import cn.sumpu.app.coolsk.domain.AuxIdentifier;*/

public class IdentifierBizImpl implements IdentifierBiz {
	
	private AuxIdentifierDao auxIdentifierDao;
	
	public void setAuxIdentifierDao(AuxIdentifierDao auxIdentifierDao) {
		this.auxIdentifierDao = auxIdentifierDao;
	}

	private DataSourceTransactionManager transactionManager;

	public void settransactionManager(
			DataSourceTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	@Override
	public String generateId(String table) throws AppBusinessException {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
		def.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);// 设置事务隔离级别
		TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", table);
			AuxIdentifier auxIdentifier = auxIdentifierDao.get(map);
			Long curValue = auxIdentifier.getValue();
			String ret = String.valueOf(curValue);
			auxIdentifier.setValue(curValue + 1);
			auxIdentifierDao.update(auxIdentifier);
			transactionManager.commit(status);// 提交事务
			return ret;
		} catch (Exception e) {
			transactionManager.rollback(status);// 回滚事务
			throw new AppBusinessException(e);
		}
	}

}
